<?php

using('Extensions.IModule');

class Admin_IModule extends IModule
{
    var $_Actions = array();

    var $_User;
    var $_DAL;


    function __construct()
    {
        // Call the IModule constructor
        parent::__construct();

        // Ensure we have references to the required objects
        if(!is_object($this->_User)) $this->_User = &Vault::Get('User');
        if(!is_object($this->_DAL))  $this->_DAL  = &Vault::Get('DAL');

        /*
         * Synchronise the module actions with the database permissions
         * to ensure there is a permission for each module action.
         */

        $actions     = array_keys($this->_Actions);
        $actions[]   = $this->_Name;
        $permissions = array();
        $rs          = $this->_DAL->Select('permission', array('label' => array('like', $this->_Name.'_%')), null, null, null, 'ASSOC');

        while($r = $rs->FetchRow())
            $permissions[] = $r['label'];

        for ($i = 0, $max = count($actions); $i < $max; $i++)
            if (!in_array(($permission = ($this->_Name.'_'.$actions[$i])), $permissions))
                $this->_DAL->Insert('permission', array('label' => $permission,
                                                        'description' => $this->_Actions[$actions[$i]]['description']));
    }

    function RegisterAction($action, $title, $perform, $description = '')
    {
        if (!isset($this->_DefaultAction))
            $this->_DefaultAction = $action;
        
        $this->_Actions[implode('_', $action)] = array('action'      => $action,
                                                       'perform'     => array(&$this, $perform),
                                                       'title'       => $title,
                                                       'description' => $description);
    }

    function GetActions()
    {
        return $this->_Actions;
    }

    function GetAction()
    {
        $args   = func_get_args();
        $action = implode('_', $args);

        if (array_key_exists($action, $this->_Actions))
            return W_ENV_URL.'/admin/module;'.$this->_Name.'/action;'.implode(',', $args).'/';
        else 
            return false;               
    }
    
    function PerformAction($action)
    {
        /*
         * Check if the requested action exists and that the
         * logged in user has access to use the action.
         */

        if (count($action) == 0)
            $action = $this->_DefaultAction;
        
        if (!array_key_exists($k = (implode('_', $action)), $this->_Actions))
            return false;

        if (!$this->_User->HasAccess($this->_Name, $action))
            return false;

        call_user_func($this->_Actions[$k]['perform']);
        return true;
    }
}

?>